﻿@using System.Collections.Specialized

@functions {

    
    private static string GenerateQueryString(int page)
    {
        NameValueCollection queryString = HttpUtility.ParseQueryString(Request.QueryString.ToString());
        queryString.Set("page", page.ToString());
        return queryString.ToString();
    }
    
    

}

@helper Links(int currentPage, int totalPages, string nextPageText, string previousPageText){
    
    totalPages = Math.Max(totalPages, 1);
    int numbersToShow = Math.Min(13, totalPages);

    int initialPage = Math.Max(currentPage - (numbersToShow / 2), 1);

    int suppostEndPage = initialPage + numbersToShow - 1;
    if (suppostEndPage > totalPages)
    {
        initialPage = initialPage - (suppostEndPage - totalPages);
    }

    bool showTwoFirst = initialPage > 1;

    if (showTwoFirst)
    {
        initialPage += 2;
        numbersToShow -= 2;
    }

    bool showTwoLasts = initialPage + numbersToShow - 1 < totalPages;

    if (showTwoLasts)
    {
        numbersToShow -= 2;
    }

<ul class="PostPager">
    @if (currentPage == 1)
    {
        <li class="PagerLinkDisabled">@previousPageText</li>
    }
    else
    { 
        <li class="PagerLink"><a href="?@GenerateQueryString(currentPage - 1)">@previousPageText</a></li>
    }
    @if (showTwoFirst)
    {
        <li class="PagerLink"><a href="?@GenerateQueryString(1)">1</a></li>
        <li class="PagerLink"><a href="?@GenerateQueryString(2)">2</a></li>
        <li class="PagerEllipses">...</li>
    }
    @foreach (int page in Enumerable.Range(initialPage, numbersToShow))
    {
        if (page == currentPage)
        {
        <li class="PagerLinkCurrent">@page</li>
        }
        else
        {
        <li class="PagerLink"><a href="?@GenerateQueryString(page)">@page</a></li>
        }
    }
    @if (showTwoLasts)
    {
        <li class="PagerEllipses">...</li>
        <li class="PagerLink"><a href="?@GenerateQueryString(totalPages - 1)">@( totalPages - 1)</a></li>
        <li class="PagerLink"><a href="?@GenerateQueryString(totalPages)">@totalPages</a></li>
    }
    @if (currentPage == totalPages)
    {
        <li class="PagerLinkDisabled">@nextPageText</li>
    }
    else
    { 
        <li class="PagerLink"><a href="?@GenerateQueryString(currentPage + 1)">@nextPageText</a></li>
    }
</ul>

    }